package com.zan.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zan.dao.CategoryMapper;
import com.zan.entity.CategoryVo;
import com.zan.entity.CategoryVo2;
import com.zan.service.CategoryService;
import com.zan.vo.ResStatus;
import com.zan.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 查询分类列表（包含所有级别的分类）
     */
    @Override
    public ResultVo listAllCategories() {
        List<CategoryVo> categoryVos = null;
        try {
            // 1.查询redis
            String categories = stringRedisTemplate.boundValueOps("categories").get();
            // 2.判断从redis中查出来的值
            if (categories != null) {
                JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, CategoryVo.class);
                categoryVos = objectMapper.readValue(categories, javaType);
            } else {
                // 如果redis中没有类别数据，则去数据库里查
                categoryVos = categoryMapper.selectAllCategories();
                stringRedisTemplate.boundValueOps("categories").set(objectMapper.writeValueAsString(categoryVos), 1, TimeUnit.DAYS);
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        if (categoryVos != null) {
            return new ResultVo(ResStatus.OK.code, "success", categoryVos);
        }
        return new ResultVo(ResStatus.NO.code, "fail", null);
    }

    /**
     * 查询一级分类，同时查询一级分类下销量最高的6个商品
     */
    @Override
    public ResultVo listFirstLevelCategories() {
        List<CategoryVo2> categories = categoryMapper.selectFirstLevelCategories();
        return new ResultVo(ResStatus.OK.code, "success", categories);
    }
}
